package com.example.nacos.ribbon.rule;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import java.util.List;
import java.util.Random;

/**
 * @ClassName : CustomVersionRule
 * @Description : 自定义根据版本号的灰度发布
 * 现在查找对应的版本号的服务，查询不到使用的随机方式，获取服务实例
 * @Author : tianshuo
 * @Date: 2021-04-05 16:49
 */
public class CustomVersionRule extends AbstractLoadBalancerRule {

    private static final Logger logger = LoggerFactory.getLogger(CustomVersionRule.class);

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;


    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private NacosServiceManager nacosServiceManager;


    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    @Override
    public Server choose(Object key) {


        logger.info("key: {}", key);
//        NamingService namingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
        String namespace = nacosDiscoveryProperties.getNamespace();
        String group = nacosDiscoveryProperties.getGroup();

        String clusterName = nacosDiscoveryProperties.getClusterName();
        String version = nacosDiscoveryProperties.getMetadata().get("version");


        DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
        String name = loadBalancer.getName();

//        try {
//            List<Instance> allInstances = namingService.getAllInstances(name);
//            for (Instance instance : allInstances) {
//
//                if(instance.)
//
//            }
//
//        } catch (NacosException e) {
//            e.printStackTrace();
//        }


        List<Server> allServers = loadBalancer.getAllServers();
        List<ServiceInstance> instances = discoveryClient.getInstances(name);
        for (ServiceInstance serviceInstance :
                instances) {
            if (serviceInstance.getMetadata() != null) {
                if (serviceInstance.getMetadata().get("version").equals(version)) {
                    Server server = createServer(serviceInstance);
                    logger.info("匹配同样版本{} 服务", version);
                    return server;
                }
            }
        }
        logger.info("未匹配的相同版本的服务,使用随机列表");
        Random random = new Random();
        int i = random.nextInt(instances.size());
        Server server = createServer(instances.get(i));
        logger.info("随机的索引为{},对应服务为{}", i, server);
        return server;
    }

    private Server createServer(ServiceInstance serviceInstance) {
        Server server = new Server(serviceInstance.getHost(), serviceInstance.getPort());
        return server;

    }
}

